import * as types from '../constants/userTypes'
import API from '../../api/request'

const API_TYPE = {
	headimgurl: '/api/user/userInfo/update',
	nickname: '/api/user/userInfo/update',
	name: '/api/user/pay/info/update',
	wechat: '/api/user/pay/info/update',
	alipay: '/api/user/pay/info/update',
	parentId: '/api/user/master/'
}

export function userInfo() {
	return async dispatch => {
		getUserInfoApi(dispatch)
	}
}

// 更新用户头像，昵称
export function updateUserInfo(info) {
	return async dispatch => {
		// 师傅ID 只能添加一个
		if (info.key === 'parentId') {
			return updateParentId(info.val, dispatch)
		} else {
			let url = API_TYPE[info.key]
			if (url) {
				updateUserInfoApi(
					url,
					{
						[info.key]: info.val
					},
					dispatch
				)
			}
		}
	}
}

// 更新用户头像，昵称
async function updateUserInfoApi(url, info, dispatch) {
	let res = await API.post(url, info)
	_updateInfo(res, dispatch)
}
async function getUserInfoApi(dispatch) {
	const url = '/api/user/userInfo'
	let res = await API.post(url)
	if (res && res.code === '200') {
		let data = res.data || {}
		dispatch(isUpdateUserInfo(data))
	} else {
		dispatch(isError(res.message))
	}
}

async function updateParentId(id, dispatch) {
	const url = '/api/user/master/' + id
	let res = await API.post(url)
	return _updateInfo(res, dispatch)
}

function _updateInfo(res, dispatch) {
	if (res && res.code === '200') {
		getUserInfoApi(dispatch)
	} else {
		dispatch(isError(res.message))
		return res.message
	}
}

export function isUpdateUserInfo(user) {
	return {
		type: types.UPDATE_USERINFO,
		user
	}
}

function isError(err) {
	return {
		type: types.IS_ERROR,
		err
	}
}
